from django.db import models
from django.utils.translation import gettext_lazy as _
from apps.users.models import User, Address
from apps.books.models import Book


class Order(models.Model):
    """订单信息"""
    
    class OrderStatus(models.TextChoices):
        PENDING = 'pending', _('待支付')
        PAID = 'paid', _('已支付')
        PROCESSING = 'processing', _('处理中')
        SHIPPED = 'shipped', _('已发货')
        DELIVERED = 'delivered', _('已送达')
        COMPLETED = 'completed', _('已完成')
        CANCELLED = 'cancelled', _('已取消')
        REFUNDED = 'refunded', _('已退款')
    
    class PaymentMethod(models.TextChoices):
        ALIPAY = 'alipay', _('支付宝')
        WECHAT = 'wechat', _('微信支付')
        CREDIT_CARD = 'credit_card', _('信用卡')
        BALANCE = 'balance', _('余额支付')
    
    order_number = models.CharField(_('订单号'), max_length=32, unique=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders', verbose_name=_('用户'))
    merchant = models.ForeignKey(User, on_delete=models.CASCADE, related_name='merchant_orders', verbose_name=_('商家'))
    shipping_address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('收货地址'))
    status = models.CharField(_('订单状态'), max_length=20, choices=OrderStatus.choices, default=OrderStatus.PENDING)
    payment_method = models.CharField(_('支付方式'), max_length=20, choices=PaymentMethod.choices, blank=True)
    
    # 金额信息
    total_amount = models.DecimalField(_('订单总金额'), max_digits=10, decimal_places=2)
    discount_amount = models.DecimalField(_('优惠金额'), max_digits=10, decimal_places=2, default=0)
    shipping_fee = models.DecimalField(_('运费'), max_digits=10, decimal_places=2, default=0)
    final_amount = models.DecimalField(_('实付金额'), max_digits=10, decimal_places=2)
    
    # 物流信息
    tracking_number = models.CharField(_('物流单号'), max_length=50, blank=True)
    express_company = models.CharField(_('快递公司'), max_length=50, blank=True)
    shipping_time = models.DateTimeField(_('发货时间'), blank=True, null=True)
    delivery_time = models.DateTimeField(_('送达时间'), blank=True, null=True)
    
    # 时间信息
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    paid_at = models.DateTimeField(_('支付时间'), blank=True, null=True)
    cancelled_at = models.DateTimeField(_('取消时间'), blank=True, null=True)
    completed_at = models.DateTimeField(_('完成时间'), blank=True, null=True)
    
    # 备注信息
    user_note = models.TextField(_('用户备注'), blank=True)
    admin_note = models.TextField(_('管理员备注'), blank=True)
    
    class Meta:
        db_table = 'orders'
        verbose_name = _('订单')
        verbose_name_plural = _('订单')
        ordering = ['-created_at']
    
    def __str__(self):
        return self.order_number
    
    @property
    def item_count(self):
        """订单商品数量"""
        return self.items.count()
    
    @property
    def can_cancel(self):
        """是否可以取消"""
        return self.status in [self.OrderStatus.PENDING, self.OrderStatus.PAID]


class OrderItem(models.Model):
    """订单商品"""
    
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', verbose_name=_('订单'))
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='order_items', verbose_name=_('图书'))
    quantity = models.IntegerField(_('数量'))
    price = models.DecimalField(_('单价'), max_digits=10, decimal_places=2)
    discount_price = models.DecimalField(_('折扣价'), max_digits=10, decimal_places=2, blank=True, null=True)
    subtotal = models.DecimalField(_('小计'), max_digits=10, decimal_places=2)
    
    class Meta:
        db_table = 'order_items'
        verbose_name = _('订单商品')
        verbose_name_plural = _('订单商品')
    
    def __str__(self):
        return f"{self.order.order_number} - {self.book.title}"


class Cart(models.Model):
    """购物车"""
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cart_items', verbose_name=_('用户'))
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='cart_items', verbose_name=_('图书'))
    quantity = models.IntegerField(_('数量'), default=1)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        db_table = 'carts'
        verbose_name = _('购物车')
        verbose_name_plural = _('购物车')
        unique_together = ['user', 'book']
    
    def __str__(self):
        return f"{self.user.username} - {self.book.title}"
    
    @property
    def subtotal(self):
        """小计金额"""
        return self.book.final_price * self.quantity


class OrderLog(models.Model):
    """订单日志"""
    
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='logs', verbose_name=_('订单'))
    action = models.CharField(_('操作'), max_length=50)
    description = models.TextField(_('描述'), blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('操作人'))
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    
    class Meta:
        db_table = 'order_logs'
        verbose_name = _('订单日志')
        verbose_name_plural = _('订单日志')
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.order.order_number} - {self.action}"
